package com.rex.saas.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rex.saas.constants.Constants;
import com.rex.saas.db.entity.SaasUserInfo;
import com.rex.saas.db.mapper.SaasUserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AuthCheckService
 * @Description:
 * @Author: zhusiyu
 * @CreateDate: 2024/12/19 10:39	//创建时间
 */
@Service
@Slf4j
public class AuthCheckService {
    @Resource
    SaasUserInfoMapper saasUserInfoMapper;

    @Resource
    RexolarApiClient rexolarApiClient;

    /**
     * 校验用户邮箱是否存在
     * @param token)
     * @return
     */
    public boolean checkToken(String token){
        if (StringUtils.isBlank(token)){
            return false;
        }
        Map<String, Object> userMap = rexolarApiClient.getAuthUser(token);
        if (CollectionUtils.isEmpty(userMap)){
            return false;
        }
        if(!Constants.TENANT_ADMIN.equals(userMap.get("authority"))
            && !Constants.SYSTEM_ADMIN.equals(userMap.get("authority"))){
            LambdaQueryWrapper<SaasUserInfo> allQueryWrapper = new LambdaQueryWrapper<>();
            allQueryWrapper.eq(SaasUserInfo::getUsername, userMap.get("email"));
            List<SaasUserInfo> list = saasUserInfoMapper.selectList(allQueryWrapper);
            if (CollectionUtils.isEmpty(list)){
                log.error("AuthCheckService user is not exist userName:{}", userMap.get("email"));
                return false;
            }
        }
        return true;
    }
}
